import 'package:flutter/material.dart';
import '../../models/product_template.dart';
import '../../services/database_helper.dart';
import '../../core/app_theme.dart';
import '../../core/snackbar_helper.dart';

class AddEditTemplateScreen extends StatefulWidget {
  final ProductTemplate? template;

  const AddEditTemplateScreen({
    super.key,
    this.template,
  });

  @override
  State<AddEditTemplateScreen> createState() => _AddEditTemplateScreenState();
}

class _AddEditTemplateScreenState extends State<AddEditTemplateScreen> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _specController = TextEditingController();
  final _priceController = TextEditingController();
  final _categoryController = TextEditingController();

  // 预定义的分类列表
  final List<String> _categories = [
    '肉类',
    '蔬菜',
    '水果',
    '粮油',
    '蛋类',
    '饮品',
    '调料',
    '其他'
  ];

  String _selectedCategory = '其他';
  bool _isSaving = false;

  @override
  void initState() {
    super.initState();
    // 如果是编辑模式，用已有数据填充表单
    if (widget.template != null) {
      _nameController.text = widget.template!.name;
      _specController.text = widget.template!.defaultSpec;
      _priceController.text = widget.template!.defaultPrice.toString();
      _selectedCategory = widget.template!.category;
      _categoryController.text = widget.template!.category;
    } else {
      _categoryController.text = _selectedCategory;
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _specController.dispose();
    _priceController.dispose();
    _categoryController.dispose();
    super.dispose();
  }

  Future<void> _saveTemplate() async {
    if (!_formKey.currentState!.validate()) return;
    if (_isSaving) return;

    setState(() {
      _isSaving = true;
    });

    try {
      final dbHelper = DatabaseHelper();
      final template = ProductTemplate(
        id: widget.template?.id,
        name: _nameController.text.trim(),
        defaultSpec: _specController.text.trim(),
        defaultPrice: double.parse(_priceController.text),
        category: _selectedCategory, // 添加分类参数
      );

      // 检查名称是否重复
      final isDuplicate = await dbHelper.isTemplateNameDuplicate(
        template.name,
        excludeId: template.id,
      );
      
      if (isDuplicate) {
        throw Exception('模板名称"${template.name}"已存在');
      }

      if (widget.template == null) {
        await dbHelper.insertProductTemplate(template);
      } else {
        await dbHelper.updateProductTemplate(template);
      }

      SnackbarHelper.showSuccess(
        context, 
        widget.template == null ? '模板添加成功' : '模板更新成功'
      );
      
      Navigator.of(context).pop();
    } catch (e) {
      SnackbarHelper.showError(context, e.toString());
    } finally {
      setState(() {
        _isSaving = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.template == null ? '添加模板' : '编辑模板',
          style: AppTheme.titleLarge,
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: ListView(
            children: [
              TextFormField(
                controller: _nameController,
                decoration: const InputDecoration(
                  labelText: '商品名称*',
                  border: OutlineInputBorder(),
                  labelStyle: AppTheme.bodyMedium,
                ),
                style: AppTheme.bodyLarge,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入商品名称';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              
              // 分类选择下拉菜单
              DropdownButtonFormField<String>(
                value: _selectedCategory,
                decoration: const InputDecoration(
                  labelText: '商品分类*',
                  border: OutlineInputBorder(),
                  labelStyle: AppTheme.bodyMedium,
                ),
                items: _categories.map((String category) {
                  return DropdownMenuItem<String>(
                    value: category,
                    child: Text(category, style: AppTheme.bodyLarge),
                  );
                }).toList(),
                onChanged: (String? newValue) {
                  setState(() {
                    _selectedCategory = newValue!;
                    _categoryController.text = newValue;
                  });
                },
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请选择商品分类';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              
              TextFormField(
                controller: _specController,
                decoration: const InputDecoration(
                  labelText: '默认规格* (如: 箱、瓶、斤)',
                  border: OutlineInputBorder(),
                  labelStyle: AppTheme.bodyMedium,
                ),
                style: AppTheme.bodyLarge,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入规格';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              
              TextFormField(
                controller: _priceController,
                decoration: const InputDecoration(
                  labelText: '默认价格*',
                  border: OutlineInputBorder(),
                  labelStyle: AppTheme.bodyMedium,
                ),
                style: AppTheme.bodyLarge,
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入价格';
                  }
                  if (double.tryParse(value) == null) {
                    return '请输入有效的金额';
                  }
                  if (double.parse(value) <= 0) {
                    return '价格必须大于0';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 24),
              
              ElevatedButton(
                onPressed: _isSaving ? null : _saveTemplate,
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
                child: _isSaving
                    ? const SizedBox(
                        height: 20,
                        width: 20,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Text('保存', style: AppTheme.bodyLarge),
              ),
            ],
          ),
        ),
      ),
    );
  }
}